package helper

// 验证器
import (
	"errors"
	"regexp" // 正则

	"github.com/go-playground/validator/v10"
)

type Validator interface {
	GetMessages() ValidatorMessages
}

type ValidatorMessages map[string]string

// ValidateStruct 获取错误信息
func ValidateStruct(request interface{}) error {

	validate := validator.New()

	// 注册身份证验证
	err := validate.RegisterValidation("checkIdCard", checkIdCard)
	if err != nil {
		panic(err.Error())
	}

	// fmt.Println(validate)
	errs := validate.Struct(request)

	if errs != nil {
		for _, err := range errs.(validator.ValidationErrors) {

			if message, exist := request.(Validator).GetMessages()[err.Field()+"."+err.Tag()]; exist {
				return errors.New(message)
			}

			// 后端问题
			panic(err.Error())

		}
	}

	return nil
}

// 给不存在添加validator库中的Tag添加额外验证

/*
*
验证身份证
*/
func checkIdCard(f validator.FieldLevel) bool {

	res, _ := regexp.Match("^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$", []byte(f.Field().String()))

	return res

	// FieldLevel contains all the information and helper functions to validate a field
	//    count := utf8.RuneCountInString(f.Field().String())
	//    //通过utf8编码，获取字符串长度
	//    if count >= 2 && count <= 12 {
	// 	   return true
	//    }
	//    return false
}
